package com.franklin.ideaplugin.easytesting.ui.execute;

import cn.hutool.core.collection.CollectionUtil;
import com.franklin.ideaplugin.api.beans.EnumClass;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiParameter;
import com.intellij.ui.components.JBTextField;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * 枚举类
 *
 * @author Ye Junhui
 * @since 2023/7/2 12:05
 */
public class EnumClassParameterFormProvider implements IParameterFormProvider {
    @Override
    public boolean isTarget(@NotNull Object defaultValue) {
        return defaultValue instanceof EnumClass;
    }

    @Override
    public ParameterTextComponent getForm(PsiParameter psiParameter, Object defaultValueOfPsiType, Object defaultValue) {
        EnumClass enumClass = (EnumClass) defaultValueOfPsiType;
        List<String> enumList = enumClass.getEnumList();
        if (CollectionUtil.isNotEmpty(enumList)) {
            ComboBox<String> comboBox = new ComboBox<>(enumList.toArray(new String[0]));
            comboBox.setToolTipText(String.format("Select an instance of enum %s", enumClass.getQualifiedName()));
            int index = enumList.indexOf(defaultValue.toString());
            if (index > -1) {
                comboBox.setSelectedIndex(index);
            } else {
                comboBox.setSelectedIndex(0);
            }
            return new ParameterTextComponent(comboBox) {
                @Override
                public String getText() {
                    return comboBox.getSelectedItem().toString();
                }
            };
        }
        JBTextField textField = new JBTextField();
        return new ParameterTextComponent(textField) {
            @Override
            public String getText() {
                return textField.getText();
            }
        };
    }
}
